package com.best.weiyi.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.best.adapter.SearchMusicListAdapter;
import com.best.weiyi.R;
import com.best.weiyi.entity.Song;
import com.best.weiyi.entity.SongDetails;
import com.best.weiyi.entity.SongList;
import com.best.weiyi.main.MainActivity;
import com.best.weiyi.main.Way;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class Search extends Fragment{
	public Way way ;
	public View v;
	EditText edit_search;
	ImageView img_search;
	ListView list_search;
	public List<Song> list = new ArrayList<Song>();
	public List<SongList> songList = new ArrayList<SongList>();
	//异步获取网络数据
	public AsyncHttpClient client;
	//dialog
	public ProgressDialog pd;
	private int index = 0;
	
	
	SongDetails details;
	String songLink;//歌曲链接地址
	String lrcLink;//歌词链接
	String songName = "";//歌曲名称
	String albumName = "";//专辑名
	String artistName = "";//艺术家名称      歌手
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v = inflater.inflate(R.layout.search_fragment, container,false);
		initView();
		/*new Thread(new SongThread(SongThread.path)).start();*/
		
		return v;
	}
	public void initView(){
		//找到组件
		edit_search = (EditText) v.findViewById(R.id.edit_search);
		img_search = (ImageView) v.findViewById(R.id.img_search);
		list_search = (ListView) v.findViewById(R.id.list_search);
		//设置点击事件
		img_search.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				pd = ProgressDialog.show(getActivity(), "", "正在拼命加载中。。。");
				//点击频幕的其他地方会退出ProgressDialog
				pd.setCancelable(true);
				String m = edit_search.getText().toString();
				String path = "http://mp3.baidu.com/dev/api/?tn=getinfo&ct=0&ie=utf-8&word="+m+"&format=json";
				client = new AsyncHttpClient();
				client.get(path, new AsyncHttpResponseHandler() {
					@SuppressLint("ShowToast")
					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						// 获得的json据
						pd.dismiss();
						String string  = new String(arg2);
						if("[]".equals(string)){
							Toast.makeText(getActivity(), "获取的数据为空,请稍后再试", 1).show();
						}else if(string.startsWith("<html>")){
							// 加入获得的数据是以<html>开头的，
							// 说明获得的是一个网页的源码，而不是json数据；
							Toast.makeText(getActivity(), "获取的数据格式不正确", 1).show();
						}else{
							//解析的一种方式
							Type type = new TypeToken<List<Song>>(){}.getType();
							Gson gson = new Gson();
							list = gson.fromJson(string, type);
							//System.out.println(list);
							//适配器
							list_search.setAdapter(new SearchMusicListAdapter(getActivity(), list));
							//Toast.makeText(getActivity(), string, 1).show();
							//设置获取的网络歌曲列表的点击事件（点击播放）
							list_search.setOnItemClickListener(new ItemClickListenerImpl());
						}
					}
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						// TODO Auto-generated method stub
						pd.dismiss();
						Toast.makeText(getActivity(), "信息获取失败，请检查网络连接", 1).show();
					}
				});
			}
		});
	}
	/**
	 * 获取的网络歌曲列表的点击事件
	 * @author jingang
	 *
	 */
	private final class ItemClickListenerImpl implements OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// 得到要搜索歌曲的id；
			String songId = list.get(arg2).getSong_id();
			// 通过song_id得到歌曲的连接；
			getLinkById(songId);			
			
		}
		
		/**
		 * 通过song_id得到歌曲的详细信息，（包括连接）
		 * @param songId
		 */
		private void getLinkById(String songId) {
			String url = "http://ting.baidu.com/data/music/links?songIds="+songId;
			AsyncHttpClient client = new AsyncHttpClient();
			client.get(url, new AsyncHttpResponseHandler() {
				String info = "";
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// 得到返回的数据；
					info = new String(arg2);
					if("[]".equals(info)){
						Toast.makeText(getActivity(), "获得的信息为空，请稍后再试", 1).show();
					}else if(info.startsWith("<html>")){                     //else if ("<html>".equals(info))
						Toast.makeText(getActivity(), "获取的信息格式不对，请稍后再试", 1).show();
					}else{
						//返回的格式正确，解析Json数据；
						parseJsonData(info);
					}
				}
				/**
				 * 获取数据json数据后解析
				 * @param info2
				 */
				private void parseJsonData(String info2){
					Gson gson = new Gson();
					// 得到选择的歌曲的详细信息；
					details = gson.fromJson(info2, SongDetails.class);
					// 歌曲的下载(在线播放)连接；
					songLink = details.getData().getSongList().get(0).getSongLink();
					// 歌词连接；
					lrcLink = details.getData().getSongList().get(0).getLrcLink();
					// 艺术家姓名；
					artistName = details.getData().getSongList().get(0).getArtistName();
					// 专辑名称；
					albumName = details.getData().getSongList().get(0).getAlbumName();
					// 歌曲名称；
					songName = details.getData().getSongList().get(0).getSongName();
					
					//m.way.play(songLink);
					
					//获得song_id后将准备播放
					try {
						new PlayerController(getActivity()).play(songLink);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					Toast.makeText(getActivity(), "没找到该首歌曲的信息", 1).show();
				}
			});
		}
	}
	/**
	 * 
	 */
	MainActivity m = new MainActivity();
	
	//private MediaPlayer player = new MediaPlayer();
	/**
	 * 
	 */
	private ProgressDialog pro = null;
	/**
	 * 准备缓冲播放
	 * @author jingang
	 *
	 */
	private class PlayerController{
		private Context mContext;
		public PlayerController(Context mContext) {
			super();
			this.mContext = mContext;
		}   
		
		public void play(String path) throws Exception{
			pro = ProgressDialog.show(mContext, "", "正在缓冲");
			pro.setCancelable(true);
			m.way.player.reset();
			
			m.way.player.setDataSource(path);
			// 异步准备；	
			m.way.player.prepareAsync();
			// 给MediaPlayer注册监听器
			m.way.player.setOnPreparedListener(new PreparedListenerImpl(mContext));
		}
	}
	/**
	 * 歌曲是否缓冲到可以播放；
	 * @author jingang
	 *
	 */
	private class PreparedListenerImpl implements OnPreparedListener{
		private Context mContext;
		public PreparedListenerImpl(Context mContext) {
			super();
			this.mContext = mContext;
		}

		@SuppressWarnings("static-access") 
		@Override
		public void onPrepared(MediaPlayer arg0) {
			//dialog歌曲的详细信息
			AlertDialog.Builder dialog = new Builder(getActivity());
			dialog.setTitle(songName+"的详细信息");
			//dialog.setMessage("Artist ["+artistName+"]\nAlbum <"+albumName+">\n"+arg0.getDuration()/1000/60+"minutes");
			//dialog.setMessage(lrcLink.toString());
			
			dialog.setCancelable(true);
			AlertDialog alert = dialog.create();
			alert.show();
			//pro.dismiss();
			//缓冲准备就绪之后，开始播放；

			arg0.start();
			//m.way.play();
			
			m.playAndPause.setImageDrawable(getResources().getDrawable(R.drawable.alarm_pause_btn));
			
						
			// 得到这首歌曲的总时长；
			int duration = arg0.getDuration();
			// 得到这首歌曲当前播放的进度；
			@SuppressWarnings("unused")
			int currentPosition = arg0.getCurrentPosition();
			m.pubProgress = 0;
			m.sb.setProgress(m.pubProgress);
			m.sb.setMax(duration);
			
			/*if(arg0.isPlaying()){
				pro.dismiss();
				m.hanlder.post(m.run);
			}else{
				pro = ProgressDialog.show(mContext, "", "正在缓冲");
				m.hanlder.removeCallbacks(m.run);
			}*/
		}
	}
}
